import util from "util";
import { readFile as oldReadFile } from "fs";
import { exec as oldExec, execFile as oldExecFile } from "child_process";

export const exec = util.promisify(oldExec);
export const execFile = util.promisify(oldExecFile);
export const readFile = util.promisify(oldReadFile);
export const execResolve = (myScript) => {
  const option = {
    // encoding: "utf8", // 如果脚本里有中文 一定要设置成这个
    // env: {
    //   // ...process.env,
    //   LANG: "zh_CN.UTF-8", // 要设置这个 否则shell的ui界面会乱码
    // },
  };
  return new Promise((resolve, reject) => {
    oldExec(myScript, option, (error, stdout, stderr) => {
      let res = {};
      if (error) {
        res = {
          type: "error",
          content: error,
        };
      } else if (stderr) {
        res = {
          type: "stderr",
          content: stderr,
        };
      } else {
        res = {
          type: "stdout",
          content: stdout,
        };
      }
      resolve(res);
    });
  });
};
export const execResolveJustContent = async (myScript) => {
  const res = await execResolve(myScript);
  return res.content;
};
